//
//  HXRegisterViewController.m
//  KD
//
//  Created by Hubery on 16/1/25.
//  Copyright © 2016年 ifly. All rights reserved.
//

#import "HXRegisterViewController.h"
#import "BarView.h"
#import "HXPersonKindTableViewCell.h"
#import "JChatConstants.h"
#import "NSString+MessageInputView.h"
#import "JCHATSetDetailViewController.h"
#import "JCHATTimeOutManager.h"

@interface HXRegisterViewController ()<BarViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *codeRange;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *codeHeight;
@property (weak, nonatomic) IBOutlet UIView *codeView;
@property (weak, nonatomic) IBOutlet UIButton *rememberBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (strong, nonatomic) BarView *barView;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTwoTextField;
@property (weak, nonatomic) IBOutlet UITextField *CodeTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property(nonatomic,assign) NSInteger registerType;
@property (weak, nonatomic) IBOutlet UIButton *messageBtn;
@property(nonatomic,assign) BOOL isRemember;

//----------- 2016 9 19 进行修改：企业注册时 添加选择人员类型
@property (nonatomic, strong) NSMutableArray <HXPersonKindListModel *> *personKindDataArray;
@property (weak, nonatomic) IBOutlet UIView *personKindBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *personKindBVLCHeight;
@property (weak, nonatomic) IBOutlet UIView *personKindView;
@property (nonatomic, retain) UIView * personBgView;
@property (nonatomic, retain) UITableView * personKindTableView;
@property (weak, nonatomic) IBOutlet UILabel *personKindLabel;
@property (nonatomic, copy) NSMutableString * users_Type;

@property (nonatomic,strong) UIButton * delectBackgroundBtn ;

@end

@implementation HXRegisterViewController

-(NSMutableArray<HXPersonKindListModel *> *)personKindDataArray{
    if (_personKindDataArray == nil) {
        _personKindDataArray = [NSMutableArray array];
    }
    return _personKindDataArray;
}
-(UIView *)personBgView{
    if (_personBgView == nil) {
        _personBgView = [[UIView alloc] initWithFrame:CGRectMake(HXSCREEN_WIDTH, 0, HXSCREEN_WIDTH, HXSCREEN_HEIGHT)];
        _personBgView.backgroundColor = HXCustomColor(170, 170, 170, 0.4);
        UIWindow * window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:_personBgView];
        
        //my--2016/9/21修改 请求数据失败 点击消失背景
        _delectBackgroundBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _delectBackgroundBtn.frame = CGRectMake(HXSCREEN_WIDTH, 0, HXSCREEN_WIDTH, HXSCREEN_HEIGHT);
        _delectBackgroundBtn.backgroundColor = [UIColor clearColor];
        [_delectBackgroundBtn addTarget:self action:@selector(delectBackgroundBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_personBgView addSubview:_delectBackgroundBtn];
        
//        //轻击一次 关闭此视图
//        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBtnAct:)];
//        tapGesture.numberOfTapsRequired = 2;
//        tapGesture.numberOfTouchesRequired = 1;
//        [_personBgView addGestureRecognizer:tapGesture];
    }
    return _personBgView;
}

//-(void)tapBtnAct:(UITapGestureRecognizer *)sender{
//    if (sender.numberOfTapsRequired == 2) {
//        [UIView animateWithDuration:0.3 animations:^{
//            self.personBgView.transform = CGAffineTransformIdentity;
//        }];
//    }
//}
-(UITableView *)personKindTableView{
    if (_personKindTableView == nil) {
        _personKindTableView = [[UITableView alloc] initWithFrame:CGRectMake(64, 144, HXSCREEN_WIDTH-64*2, HXSCREEN_HEIGHT-144*2) style:UITableViewStylePlain];
        [self.personBgView addSubview:_personKindTableView];
        _personKindTableView.delegate = self;
        _personKindTableView.dataSource = self;
        
        //创建btn按钮
        UIButton * selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(_personKindTableView.right-64, _personKindTableView.bottom, 64, 30)];
        [self.personBgView addSubview:selectBtn];
        [selectBtn setTitle:@"确定" forState:UIControlStateNormal];
        selectBtn.backgroundColor = [UIColor whiteColor];
        [selectBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        selectBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        [selectBtn addTarget:self action:@selector(selectBtnAct:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _personKindTableView;
}

-(void)selectBtnAct:(UIButton *)sender{
    
    //[self getPeopleList];
    
    NSMutableString * typeName = [NSMutableString string];
    NSMutableString * typeValue = [NSMutableString string];
    for (int i = 0; i < self.personKindDataArray.count; i++) {
        HXPersonKindListModel * model = self.personKindDataArray[i];
        if (model.isSelected) {
            [typeName appendFormat:@"%@,",model.typeName];
            [typeValue appendFormat:@"%@,",model.typeValue];
        }
    }
    if (typeName.length > 0) {
        self.personKindLabel.textColor = [UIColor blackColor];
        typeName = (NSMutableString *)[typeName substringToIndex:typeName.length-1];
        typeValue = (NSMutableString *)[typeValue substringToIndex:typeValue.length-1];
        self.users_Type = typeValue;
    }else{
        self.personKindLabel.textColor = HXCustomColor(200, 200, 200, 1.0);
        typeName = [NSMutableString stringWithFormat:@"请选择人员类型"];
    }
    self.personKindLabel.text = typeName;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.personBgView.transform = CGAffineTransformIdentity;
        self.delectBackgroundBtn.transform = CGAffineTransformIdentity;
    }];
}

- (void)delectBackgroundBtnClick {
    
    [UIView animateWithDuration:0.3 animations:^{
        self.personBgView.transform = CGAffineTransformIdentity;
    }];
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.personKindDataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HXPersonKindTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"HXPersonKindTableViewCell"];
    if (!cell) {
        cell = [[HXPersonKindTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HXPersonKindTableViewCell"];
    }
    
    cell.listModel = self.personKindDataArray[indexPath.row];
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HXPersonKindListModel * listModel = self.personKindDataArray[indexPath.row];
    //修改模型数据
    listModel.isSelected = !listModel.isSelected;
    //刷新当前行
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"人员类型";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.users_Type = [NSMutableString string];
    self.registerType = UserTypeManage;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"back" highImage:@"back" target:self action:@selector(dismiss)];
    [self setBarBtn];
    [self.registerBtn setTitle:@"主管注册" forState:UIControlStateNormal];
    [self getPeopleList];
}

/**
 获取人员类型
 */
- (void)getPeopleList {
    
    [NetworkAPI getPersonKindWithCkind:@"15"
                               success:^(HXPersonKindModel *result) {
                                   if ([result.code isEqualToString:@"200"]) {
                                       
                                       for (HXPersonKindListModel * model in result.resultlist) {
                                           model.isSelected = NO;
                                           [self.personKindDataArray addObject:model];
                                       }
                                       [self.personKindTableView reloadData];
                                       //self.delectBackgroundBtn.enabled = NO;
                                   }
                                   else {
                                       [SVProgressHUD showErrorWithStatus:@"获取人员类型失败"];
                                       //self.delectBackgroundBtn.enabled = YES;
                                   }
                                   
                               } failure:^(NSError *err) {
                                   [SVProgressHUD showErrorWithStatus:@"获取人员类型失败"];
                                   //self.delectBackgroundBtn.enabled = YES;
                               }];
}

- (IBAction)personKindBtnAct:(UIButton *)sender {
    [UIView animateWithDuration:0.3 animations:^{
        self.personBgView.transform = CGAffineTransformMakeTranslation(-HXSCREEN_WIDTH, 0);
        self.delectBackgroundBtn.transform = CGAffineTransformMakeTranslation(-HXSCREEN_WIDTH, 0);
    }];
}



- (IBAction)rememberBtnClick:(UIButton *)sender {
    self.rememberBtn.selected = !self.rememberBtn.selected;
    if (self.rememberBtn.selected) {
        self.isRemember = YES;
        [self.rememberBtn setBackgroundImage:[UIImage imageNamed:@"true"] forState:UIControlStateNormal];
        [self.rememberBtn setBackgroundColor:MAINCOLOR];
    }else{
        self.isRemember = NO;
        [self.rememberBtn setBackgroundImage:nil forState:UIControlStateNormal];
        [self.rememberBtn setBackgroundColor:[UIColor whiteColor]];
    }
}

-(void)setBarBtn{
    BarView  *barView = [[BarView alloc]initWithFrame:CGRectMake(0, 64, HXSCREEN_WIDTH, 40)];
    self.barView = barView;
    barView.barCollectionDelegate = self;
    barView.childViewControllerTitles = @[@"主管注册",@"企业注册"];
    barView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.barView];
    
    //设置界面
    self.codeHeight.constant = 0;
    self.codeRange.constant = 0;
    self.codeView.hidden = YES;
    self.personKindBVLCHeight.constant = 0;
    self.personKindBgView.hidden = YES;
    self.personKindView.layer.borderWidth = 0.5f;
    self.personKindView.layer.borderColor = HXCustomColor(200, 200, 200, 1.0).CGColor;
    self.personKindView.layer.cornerRadius = 10.f;
    self.personKindLabel.textColor = HXCustomColor(200, 200, 200, 1.0);
    
    //阅读按钮
    self.rememberBtn.layer.masksToBounds = YES;
    self.rememberBtn.layer.borderWidth = 1;
    self.rememberBtn.layer.borderColor = [UIColor darkGrayColor].CGColor;
    
    //设置文字
    NSMutableAttributedString *title1 = [[NSMutableAttributedString alloc] initWithString:@"用户服务条款"];
    NSRange titleRange1 = {0,[title1 length]};
    [title1 addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:titleRange1];
    [title1 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:titleRange1];
//    [self.messageLabel setAttributedText:title1];
    [self.messageBtn setAttributedTitle:title1 forState:UIControlStateNormal];
    [self.messageBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //注册按钮
    self.registerBtn.layer.masksToBounds = YES;
    self.registerBtn.layer.cornerRadius = 11;
}

- (void)barCollectionView:(BarView *)barCollectionView didSelectionItemAtIndex:(NSUInteger)index{
    if (index == UserTypeManage) {
        self.barView.page = 0;//KVO控制btn下面长条位置用
        [self.registerBtn setTitle:@"主管注册" forState:UIControlStateNormal];
        self.registerType = UserTypeManage;//主管
        self.codeHeight.constant = 0;
        self.codeRange.constant = 0;
        self.codeView.hidden = YES;
        self.personKindBVLCHeight.constant = 0;
        self.personKindBgView.hidden = YES;
        
        self.phoneTextField.text = @"";
        self.pwdTwoTextField.text = @"";
        self.CodeTextField.text = @"";
        self.pwdTextField.text = @"";
        
    }else if(index == UserTypeCorp){
        [self.registerBtn setTitle:@"企业注册" forState:UIControlStateNormal];
        self.barView.page = 1;
        self.registerType = UserTypeCorp;//企业
        self.codeHeight.constant = 42;
        self.codeRange.constant = 8;
        self.codeView.hidden = NO;
        self.personKindBVLCHeight.constant = 42.f;
        self.personKindBgView.hidden = NO;
        
        self.phoneTextField.text = @"";
        self.pwdTwoTextField.text = @"";
        self.CodeTextField.text = @"";
        self.pwdTextField.text = @"";
    }else{
        self.barView.page = 0;
        [self.registerBtn setTitle:@"主管注册" forState:UIControlStateNormal];
        self.registerType = UserTypeManage;//主管
        self.codeHeight.constant = 42;
        self.codeRange.constant = 8;
        self.codeView.hidden = NO;
    }
}

- (IBAction)registerBtnClick:(id)sender {
    if (!self.isRemember) {
        [SVProgressHUD showErrorWithStatus:@"请阅读并同意服务条款"];
        return;
    }
    if ([self.phoneTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    if (![GlobalUtil validateMobile:self.phoneTextField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入合法手机号"];
        return;
    }
    if ([self.pwdTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    if ([self.pwdTwoTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请确认密码"];
        return;
    }
    if (![self.pwdTwoTextField.text isEqualToString:self.pwdTextField.text]) {
        [SVProgressHUD showErrorWithStatus:@"输入密码不一致"];
        return;
    }
    if ([GlobalUtil isNilValue:self.users_Type]) {
        [SVProgressHUD showErrorWithStatus:@"请选择人员类型"];
        return;
    }
    if ([self.personKindLabel.text isEqualToString:@"请选择人员类型"]) {
        [SVProgressHUD showErrorWithStatus:@"请选择人员类型"];
        return;
    }

    if (self.registerType == UserTypeManage) {//主管注册
        self.CodeTextField.text = @"";
        self.users_Type = [NSMutableString string];
    }else if(self.registerType == UserTypeCorp){//公司注册
        if ([self.CodeTextField.text isEqualToString:@""]) {
            [SVProgressHUD showErrorWithStatus:@"请输入组织机构代码"];
            return;
        }
    }else{//其他情况 默认公司注册
        //NSAssert(0, @"主管注册还是公司注册参数出错");
    }//www
    [SVProgressHUD showWithStatus:@"正在注册" ];
    [NetworkAPI registerWithName:self.CodeTextField.text
                  users_CellPhoneNum:self.phoneTextField.text
                  users_PassWord:self.pwdTextField.text
                  users_CorpName:@""
                  users_Kind:[NSString stringWithFormat:@"%ld",(long)self.registerType]
     Users_Type:self.users_Type
        success:^(HXRegisterModel *result) {
            [UserDefaultHandler saveUserDetault:result.result.Users_CellPhoneNum key:kUsers_CellPhoneNum];
            [UserDefaultHandler runSave];
            [SVProgressHUD dismiss];
            if ([result.code isEqualToString:@"200"]) {
                [SVProgressHUD showSuccessWithStatus:@"注册成功"];
                [UserDefaultHandler saveUserDetault:result.result.Users_CellPhoneNum key:kUsers_CellPhoneNum];
                [self newRegisterJPushUser:result.result.Users_Alias PassWord:result.result.Users_PassWord];
                
            }else{
                NSString * message;
                if (result.msg.length > 0) {
                    
                    message = result.msg;
                }else {
                    message = @"您的手机号与组织机构代码社会统一信用代码有误或无法匹配，请您登录“青岛一体化系统”注册、完善企业与人员信息。电话0532-85871505 转 6";
                }
                
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"注册失败" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alert show];
            }
        } failure:^(NSError *err) {
                [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }];
}

//新极光注册
- (void)newRegisterJPushUser:(NSString *)userName PassWord:(NSString *)passWord {
    
    NSString *username = userName.stringByTrimingWhitespace;
    NSString *password = passWord.stringByTrimingWhitespace;
    
    [MBProgressHUD showMessage:@"正在注册" view:self.view];
    [[JCHATTimeOutManager ins] startTimerWithVC:self];
    [JMSGUser registerWithUsername:username
                          password:password
                 completionHandler:^(id resultObject, NSError *error) {
                     [[JCHATTimeOutManager ins] stopTimer];
                     if (error == nil) {
                         [[JCHATTimeOutManager ins] startTimerWithVC:self];
                         [JMSGUser loginWithUsername:username
                                            password:password
                                   completionHandler:^(id resultObject, NSError *error) {
                                       [[JCHATTimeOutManager ins] stopTimer];
                                       if (error == nil) {
                                           
                                           [[NSUserDefaults standardUserDefaults] setObject:username forKey:kuserName];
                                           [[NSUserDefaults standardUserDefaults] setObject:username forKey:klastLoginUserName];
                                           [UserDefaultHandler saveUserDetault:@"yes" key:kIsRegisterJpush];//注册成功
                                           [self dismissViewControllerAnimated:YES completion:nil];
                                       }
                                       else if (error.code == 898001) {
                                           
                                           [UserDefaultHandler saveUserDetault:@"yes" key:kIsRegisterJpush];//已经注册过
                                           [self dismissViewControllerAnimated:YES completion:nil];
                                       }
                                       else {
                                           DDLogDebug(@"login fail error  %@",error);
                                           NSString *alert = [JCHATStringUtils errorAlert:error];
                                           alert = [JCHATStringUtils errorAlert:error];
                                           [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                           [MBProgressHUD showMessage:alert view:self.view];
                                           DDLogError(alert);
                                       }
                                   }];
                     } else {
                         
                         NSString *alert = @"注册失败";
                         alert = [JCHATStringUtils errorAlert:error];
                         [MBProgressHUD hideHUDForView:self.view animated:YES];
                         [MBProgressHUD showMessage:alert view:self.view];
                     }
                 }];
    
}

-(void)dismiss{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
